//
//  LoginViewController.m
//  AILock
//
//  Created by 谭亚明 on 2020/6/19.
//  Copyright © 2020 tym. All rights reserved.
//

#import "LoginViewController.h"
#import "TopMenuView.h"
#import "LMJBaseResponse.h"
#import "FamilyService.h"
#import "Sizes.h"
#import "WebViewController.h"
#import "NSAttributedString+YYText.h"
#import "YYLabel.h"
#import "MBProgressHUD+WJExtension.h"
#import "UserTool.h"
#import <YYModel.h>
#import "UserModel.h"
// 引入 JPush 功能所需头文件
#import "JPUSHService.h"
// iOS10 注册 APNs 所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
#import "WellcomViewController.h"
#import "DeviceInfo.h"
#import "ForgetViewController.h"
#import "RegsiView.h"
#import "LoginView.h"
#import "Fonts.h"
#import "WHToast.h"
#import "UIView+ZFFrame.h"
#import "Colors.h"
#import "UserService.h"
@interface LoginViewController ()<TopMenuViewDelegate,UIScrollViewDelegate,UINavigationControllerDelegate>

@property(nonatomic,weak) IBOutlet UIView *contView;

//切换按钮
@property (nonatomic,strong)    TopMenuView         *menuView;
//子view
@property (nonatomic,strong)    UIScrollView     *scrollView;

@property (nonatomic,strong)    LoginView       *loginView;
@property (nonatomic,strong)    RegsiView       *regiView;

@property(nonatomic,strong) UserService  *userService;
@property(nonatomic,strong) FamilyService *familyService;

@property(nonatomic,strong)  UIButton   *agBtn;
@property(nonatomic,weak)    YYLabel *bottomLab;
@end

@implementation LoginViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUI];
    self.navigationController.delegate = self;
    [self.contView addSubview:self.menuView];
    [self addLineView];
    [self.contView addSubview:self.scrollView];
    [self.scrollView addSubview:self.loginView];
    [self.scrollView addSubview:self.regiView];
    
    [self initTextLabel];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController navigationController:self.navigationController willShowViewController:self animated:YES];
    
    if ([UserTool getLogInUser]) {
        if (self.isWellcom) {
            WellcomViewController *wellComeVC = [[WellcomViewController alloc] init];
            [self.navigationController pushViewController:wellComeVC animated:YES];
            self.isWellcom = NO;
        }else{
            [self getCurrentFamily];
        }
    }
}

-(void)initTextLabel{
    
    YYLabel  *textLab = [[YYLabel alloc] initWithFrame:CGRectMake((ScreenWidth)/2 - 330/2+30, ScreenHeight - SafeBottomMargin - 40, 330, 16)];
    NSString *agreementText = @"我已阅读并接受《许可协议》、《隐私政策》及《法律申明》";
    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:agreementText];
    text.yy_font = [UIFont systemFontOfSize:10];
    text.yy_alignment = NSTextAlignmentLeft;
    text.yy_color = rgba(74, 74, 74);
    [text yy_setTextHighlightRange:NSMakeRange(7, 6) color:MainColor backgroundColor:nil  tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        WebViewController *webView = [[WebViewController alloc] init];
        webView.gotoURL = @"http://cs.xundatong.net/lockinstall/agreement.html";
        webView.titleStr = @"许可协议";
        [self.navigationController pushViewController:webView animated:YES];
    }];
    [text yy_setTextHighlightRange:NSMakeRange(14, 6) color:MainColor backgroundColor:nil  tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        WebViewController *webView = [[WebViewController alloc] init];
        webView.gotoURL = @"http://cs.xundatong.net/lockinstall/privacy.html";
        webView.titleStr = @"隐私政策";
        [self.navigationController pushViewController:webView animated:YES];
    }];
    [text yy_setTextHighlightRange:NSMakeRange(21, 6) color:MainColor backgroundColor:nil  tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        
        WebViewController *webView = [[WebViewController alloc] init];
        webView.gotoURL = @"http://cs.xundatong.net/lockinstall/legalNotices.html";
        webView.titleStr = @"法律申明";
        [self.navigationController pushViewController:webView animated:YES];
    }];
    textLab.attributedText = text;
    [self.view addSubview:textLab];
    textLab.hidden = YES;
    self.bottomLab = textLab;
    
    _agBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _agBtn.frame = CGRectMake(ScreenWidth/2 - 330/2+8,  ScreenHeight - SafeBottomMargin - 43, 22, 22);
    [_agBtn setImage:[UIImage imageNamed:@"icon_login7"] forState:UIControlStateNormal];
    [_agBtn addTarget:self action:@selector(clickAgreeImage:) forControlEvents:UIControlEventTouchUpInside];
    _agBtn.selected = YES;
    _agBtn.hidden = YES;
    [self.view addSubview:_agBtn];
}

-(void)clickAgreeImage:(UIButton*)sender{
    
    _agBtn.selected = !_agBtn.selected;
    if (_agBtn.selected) {
        [_agBtn setImage:[UIImage imageNamed:@"icon_login7"] forState:UIControlStateNormal];
    }else{
        [_agBtn setImage:[UIImage imageNamed:@"icon_login1"] forState:UIControlStateNormal];
    }
}

-(UserService*)userService{
    if (_userService == nil) {
        _userService = [[UserService alloc] init];
    }
    return _userService;;
}

-(FamilyService*)familyService{
    if (_familyService == nil) {
        _familyService = [[FamilyService alloc] init];
    }
    return _familyService;
}

-(void)addLineView{
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, self.menuView.zf_height, self.scrollView.zf_width, 1)];
    lineView.backgroundColor = rgba(242, 242, 242);
    [self.contView addSubview:lineView];
}

-(void)setUI{
    self.contView.zf_width = ScreenWidth - 30;
    self.contView.layer.backgroundColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1.0].CGColor;
    self.contView.layer.cornerRadius = 15;
    self.contView.layer.shadowColor = [UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:0.5].CGColor;
    self.contView.layer.shadowOffset = CGSizeMake(0,-6.5);
    self.contView.layer.shadowOpacity = 1;
    self.contView.layer.shadowRadius = 14;
}

//注册
-(void)registerMobile:(NSString*)mobile password:(NSString*)password code:(NSString*)code{
    
    if (!self.agBtn.selected) {
        [WHToast showMessage:@"请接受用户协议" duration:2 finishHandler:nil];
        return;
    }
    
    [MBProgressHUD wj_showActivityLoading:@"" toView:self.view];
    TYMWeak(self);
    [self.userService getResiterMobile:mobile password:password channel:@"2" regiterWay:@"0" validateionCode:code completion:^(NSError * _Nonnull error, LMJBaseResponse * _Nonnull response) {
        [MBProgressHUD wj_hideHUDForView:weakself.view];
        if (!response.code) { //成功失败
            [WHToast showMessage:@"注册成功" duration:2 finishHandler:^{
                [weakself.menuView selectItemChangedWithSelectedIndex:0];
                [weakself  refreshWithTag:0];
                
                
                [weakself loginWithPhone:mobile password:password];
            }];
        }else{
            [WHToast showMessage:response.message duration:2 finishHandler:nil];
        }
    }];
}

//登录
-(void)loginWithPhone:(NSString *)phone password:(NSString *)password{
    
    [MBProgressHUD wj_showActivityLoading:@"" toView:self.view];
    TYMWeak(self);
    [self.userService getLoginWithMobile:phone password:password completion:^(LMJBaseResponse *reson, UserModel * _Nonnull user) {
        [MBProgressHUD wj_hideHUDForView:weakself.view];
        if (!reson.message) {
            if (user) {
                [UserTool setUserInfo:user completion:^(BOOL state) {
                    if (state) {
                        [weakself getCurrentFamily];
                    }
                }];
            }
        }else{
            [WHToast showMessage:reson.message duration:2 finishHandler:nil];
        }
    }];
}

-(void)getCurrentFamily{
    TYMWeak(self);
    [self.familyService getFamilyUserCurrentCompletion:^(LMJBaseResponse  *respns, FamilyModel * _Nonnull response) {
        if (respns.code == 0) {
            if (response.familyId) { //有默认家庭
                [UserTool setFamily:response completion:^(BOOL state) {
                    [weakself dismissViewControllerAnimated:YES completion:nil];
                }];
            }else{  //没有默认家庭
                WellcomViewController *wellComeVC = [[WellcomViewController alloc] init];
                [weakself.navigationController pushViewController:wellComeVC animated:YES];
            }
        }else{
            [WHToast showMessage:respns.message duration:2 finishHandler:^{
            }];
        }
    }];
}

-(void)getVerificationCode:(NSString*)mobile{
    if (mobile.length < 11) {
        [WHToast showMessage:@"请检查你输入的手机号码" duration:2 finishHandler:nil];
        return;
    }
    [MBProgressHUD wj_showActivityLoading:@"" toView:self.view];
    TYMWeak(self);
    [self.userService getValidteionCode:mobile completion:^(NSError * _Nonnull error, LMJBaseResponse * _Nonnull response) {
        [MBProgressHUD wj_hideHUDForView:weakself.view];
        if (response.code == 0) {
            [weakself.regiView startCountDown];
        }else{
            [WHToast showMessage:response.message duration:2 finishHandler:nil];
        }
    }];
}

#pragma mark- 滑动切换切换子View
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if (scrollView == self.scrollView) {
        CGFloat pageWidth = scrollView.frame.size.width;
        NSInteger page = scrollView.contentOffset.x / pageWidth;
        NSInteger selectedBtnTag = page;
        [self.menuView selectItemChangedWithSelectedIndex:selectedBtnTag];
        
        if (selectedBtnTag) {
            self.bottomLab.hidden = NO;
            self.agBtn.hidden = NO;
        }else{
            self.bottomLab.hidden = YES;
            self.agBtn.hidden = YES;
        }
    }
    
}

#pragma mark- TopMenuViewDelegate
- (void)refreshWithTag:(NSInteger)menuTag{
    [self.scrollView scrollRectToVisible:CGRectMake(self.contView.zf_width * menuTag, 0, self.contView.zf_width, self.scrollView.zf_height) animated:YES];
    
    if (menuTag) {
        self.bottomLab.hidden = NO;
        self.agBtn.hidden = NO;
    }else{
        self.bottomLab.hidden = YES;
        self.agBtn.hidden = YES;
    }
}

#pragma mark- 懒加载
- (TopMenuView *)menuView{
    if( _menuView == nil){
        NSArray *btnTitleArr = @[@"登录",@"注册"];
        _menuView = [[TopMenuView alloc]initWithFrame:CGRectMake(0, 0 , _contView.zf_width , 44) andTitleArray:btnTitleArr titleColor:rgba(74, 74, 74) titleHeighColor:rgba(74, 74, 74) lineColor:rgba(53, 54, 70) lineWidth:12 lineHeight:3 withFont:Font_Regular(16)];
        _menuView.layer.backgroundColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1.0].CGColor;
        _menuView.layer.cornerRadius = 15;
        _menuView.layer.shadowColor = [UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:0.5].CGColor;
        _menuView.layer.shadowOffset = CGSizeMake(0,1);
        _menuView.layer.shadowOpacity = 1;
        _menuView.layer.shadowRadius = 0;
        _menuView.delegate = self;
    }
    return _menuView;
}

- (UIScrollView *)scrollView{
    if( _scrollView == nil){
        _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, self.menuView.zf_height+1, self.contView.zf_width, 400)];
        
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.pagingEnabled = YES;
        _scrollView.delegate = self;
        _scrollView.bounces = NO;
    }
    _scrollView.contentSize = CGSizeMake(2*self.contView.zf_width, 1);
    return _scrollView;
}

-(LoginView*)loginView{
    if (_loginView == nil) {
        _loginView = [[NSBundle mainBundle]loadNibNamed:@"LoginView" owner:self options:nil].lastObject;
        _loginView.frame = CGRectMake(0, 0, ScreenWidth - 30, self.scrollView.zf_height);
        TYMWeak(self);
        _loginView.forgetPasswordBlock = ^{
            
            [weakself.navigationController pushViewController:[ForgetViewController new] animated:YES];
        };
        _loginView.loginBlock = ^(NSString * _Nonnull phoneStr, NSString * _Nonnull password) {
            [weakself loginWithPhone:phoneStr password:password];
        };
    }
    return _loginView;
}

-(RegsiView *)regiView{
    if (_regiView == nil) {
        _regiView = [[NSBundle mainBundle]loadNibNamed:@"RegsiView" owner:self options:nil].lastObject;
        _regiView.frame = CGRectMake(self.scrollView.zf_width, 0, self.menuView.zf_width, self.scrollView.zf_height);
        TYMWeak(self);
        _regiView.getCodeBlock = ^(NSString *mobile){
            [weakself getVerificationCode:mobile];
        };
        
        _regiView.registerBlock = ^(NSString * _Nonnull mobile, NSString * _Nonnull password, NSString * _Nonnull code) {
            [weakself registerMobile:mobile password:password code:code];
        };
    }
    return _regiView;
}

#pragma mark - UINavigationControllerDelegate
// 将要显示控制器
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    // 判断要显示的控制器是否是自己
    BOOL isShowHomePage = [viewController isKindOfClass:[self class]];
    
    [self.navigationController setNavigationBarHidden:isShowHomePage animated:YES];
}

-(void)dealloc{
    NSLog(@"++++++++++登陆页面释放");
    self.navigationController.delegate = nil;
}

@end
